/**
 * 
 */
package com.ai.notices.web.controller.busi;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ai.notices.common.util.DateUtils;
import com.ai.notices.common.util.PagedResult;
import com.ai.notices.dao.mysql.model.AuthStaff;
import com.ai.notices.dao.mysql.model.OrdInfo;
import com.ai.notices.dao.mysql.model.OrdInfoImp;
import com.ai.notices.service.interfaces.IGdsInfoSV;
import com.ai.notices.service.interfaces.IOrderInfoSV;
import com.ai.notices.service.resp.GdsInfoResp;
import com.ai.notices.web.FileUtils;
import com.ai.notices.web.system.AppBaseController;
import com.ai.notices.web.system.excel.ExcelExport;
import com.ai.notices.web.system.util.StaffSessionUtil;
import com.alibaba.fastjson.JSONObject;

/**
 * @author chenjf6 号码管理
 */
@Controller
@RequestMapping(value = "/order_info")
public class OrderInfoController extends AppBaseController {
	
    private static final Logger log = Logger.getLogger(OrderInfoController.class);

    @Autowired
    private IOrderInfoSV orderInfoSV;
    
    @Autowired
    private IGdsInfoSV gdsInfoSV;
	
	@RequestMapping(value = { "/order_init" })
	public String orderInit(Model model) throws Exception {
		
		return "/busi/order/order-init";
	}
	
	@RequestMapping(value = { "/order_list" }, method = { RequestMethod.POST })
	public String orderList(Model model, OrdInfo ordInfo, Integer pageNo, Integer pageSize) throws Exception {
		PagedResult<OrdInfo> pageResult = orderInfoSV.queryOrdInfoByPage(ordInfo, pageNo, pageSize);
        model.addAttribute("data", pageResult);
		return "/busi/order/order-list";
	}
	
	@RequestMapping(value = { "/order_import_init" })
	public String orderImportInit(Model model) throws Exception {
		
		return "/busi/order/order-import";
	}
	
	@RequestMapping(value = { "/order_import" }, method = { RequestMethod.POST })
	@ResponseBody
	public JSONObject orderImport(@RequestParam("orderFile") MultipartFile mfile, Model model,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		AuthStaff authStaff = StaffSessionUtil.getStaffInfo(request.getSession());
		JSONObject ret = new JSONObject();
		List<List<Map<String, String>>> orderInfos = FileUtils.file2List(mfile);
		if (CollectionUtils.isEmpty(orderInfos) || CollectionUtils.isEmpty(orderInfos.get(0))) {
			ret.put("flag", false);
			ret.put("msg", "上传的文件格式不正确（如：文件为空、导入文件不支持）");
			return ret;
		}
		String strFileNmae = mfile.getOriginalFilename();
		if (StringUtils.isNotBlank(strFileNmae)) {
			strFileNmae = strFileNmae.substring(0, strFileNmae.lastIndexOf("."));
		}
		String batchId = FileUtils.getId();
		try {
			orderInfoSV.saveOrdInfoImp(orderInfos.get(0), batchId, authStaff, strFileNmae);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		}
        ret.put("flag", true);
		ret.put("msg", batchId);
		return ret;
	}
	
	@RequestMapping(value = { "/save_order" }, method = { RequestMethod.POST })
	@ResponseBody
	public JSONObject saveOrder(@RequestParam("batchId") String batchId, Model model,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		AuthStaff authStaff = StaffSessionUtil.getStaffInfo(request.getSession());
		JSONObject ret = new JSONObject();
		try {
			orderInfoSV.saveOrdInfo(batchId, authStaff);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		}
        ret.put("flag", true);
		ret.put("msg", batchId);
		return ret;
	}
	
	@RequestMapping(value = { "/order_import_list" }, method = { RequestMethod.POST })
	public String orderImportList(Model model, OrdInfoImp imp, Integer pageNo, Integer pageSize) throws Exception {
		PagedResult<OrdInfoImp> pageResult = orderInfoSV.queryOrdInfoImpByPage(imp, pageNo, pageSize);
        model.addAttribute("data", pageResult);
		return "/busi/order/order-import-list";
	}
	
	@RequestMapping(value = { "/order_import_success_list" }, method = { RequestMethod.POST })
	public String orderImportSuccessList(Model model, OrdInfoImp imp, Integer pageNo, Integer pageSize) throws Exception {
		PagedResult<OrdInfoImp> pageResult = orderInfoSV.queryOrdInfoImpByPage(imp, pageNo, pageSize);
        model.addAttribute("data", pageResult);
		return "/busi/order/order-import-success-list";
	}
	
	@RequestMapping(value = { "/order_import_fail_list" }, method = { RequestMethod.POST })
	public String orderImportFailList(Model model, OrdInfoImp imp, Integer pageNo, Integer pageSize) throws Exception {
		PagedResult<OrdInfoImp> pageResult = orderInfoSV.queryOrdInfoImpByPage(imp, pageNo, pageSize);
        model.addAttribute("data", pageResult);
		return "/busi/order/order-import-fail-list";
	}

    @RequestMapping(value = { "/order_export" }, method = { RequestMethod.POST })
    public void orderExport(OrdInfo ordInfo, HttpServletResponse response) throws Exception {
    	
        List<OrdInfo> tmpList = orderInfoSV.queryOrdInfoLst(ordInfo);
        List<String> titleList = new ArrayList<String>();
        titleList.add("物流运单编号");
        titleList.add("订单编号");
        titleList.add("身份证号码");
        titleList.add("收件人名");
        titleList.add("收件人电话");
        titleList.add("收货人地址");
        titleList.add("收件人邮编");
        titleList.add("毛重（kg）");
        titleList.add("商品货号");
        titleList.add("商品名称");
        titleList.add("商品规格型号");
        titleList.add("商品编码");
        titleList.add("序号");
        titleList.add("数量");
        titleList.add("件数");
        titleList.add("法定数量");
        titleList.add("计量单位代码");
        titleList.add("法定计量单位");
        titleList.add("第二计量单位");
        titleList.add("单价");
        titleList.add("总价");
        titleList.add("商品税号");
        titleList.add("主运单号");

        List<List<String>> dataList = new ArrayList<List<String>>();
        String xlsName = "导出订单表"+DateUtils.getDateString(DateUtils.YYYYMMDDHHMMSS)+".xls";
        if(CollectionUtils.isEmpty(tmpList)){
            ExcelExport.exportExcelFile(titleList, dataList, xlsName, 0, request, response);
            return;
        }
        for(OrdInfo tmpOrdInfo : tmpList){
            List<String> data = new ArrayList<String>();
            data.add(tmpOrdInfo.getExpressNo());
            data.add(tmpOrdInfo.getOrdId()==null?"":String.valueOf(tmpOrdInfo.getOrdId()));
            data.add(tmpOrdInfo.getIdentityCard());
            data.add(tmpOrdInfo.getRecName());
            data.add(tmpOrdInfo.getRecPhone());
            data.add(tmpOrdInfo.getRecAddr());
            data.add(tmpOrdInfo.getRecZipCode());
            data.add(tmpOrdInfo.getWeight()==null?"":String.valueOf(tmpOrdInfo.getWeight()));
            data.add(tmpOrdInfo.getGdsId()==null?"":String.valueOf(tmpOrdInfo.getGdsId()));
            data.add(tmpOrdInfo.getGdsName());
            data.add(tmpOrdInfo.getSpec());
            data.add(tmpOrdInfo.getGdsCode());
            data.add(tmpOrdInfo.getCustNo()==null?"":String.valueOf(tmpOrdInfo.getCustNo()));
            data.add(tmpOrdInfo.getNum()==null?"":String.valueOf(tmpOrdInfo.getNum()));
            data.add(tmpOrdInfo.getExpressNum()==null?"":String.valueOf(tmpOrdInfo.getExpressNum()));
            data.add(tmpOrdInfo.getLegalNum()==null?"":String.valueOf(tmpOrdInfo.getLegalNum()));
            data.add(tmpOrdInfo.getMeasureCode());
            data.add(tmpOrdInfo.getLegalMeasureUnit());
            data.add(tmpOrdInfo.getSecMeasureUnit());
            data.add(tmpOrdInfo.getPrice()==null?"":String.valueOf((double)(Math.round(tmpOrdInfo.getPrice())/100.0)));
            data.add(tmpOrdInfo.getTotalMoney()==null?"":String.valueOf((double)(Math.round(tmpOrdInfo.getTotalMoney())/100.0)));
            data.add(tmpOrdInfo.getRecordCode());
            data.add(tmpOrdInfo.getMainOrdId());
            dataList.add(data);
        }
        ExcelExport.exportExcelFile(titleList, dataList, xlsName, 0, request, response);
    }

    @RequestMapping(value = { "/pay_export" }, method = { RequestMethod.POST })
    public void payExport(OrdInfo ordInfo, HttpServletResponse response) throws Exception {
    	
        List<OrdInfo> tmpList = orderInfoSV.queryOrdInfoLst(ordInfo);
        List<String> titleList = new ArrayList<String>();
        titleList.add("订单编号");
        titleList.add("支付交易流水号");
        titleList.add("支付金额");
        titleList.add("支付时间");

        List<List<String>> dataList = new ArrayList<List<String>>();
        String xlsName = "导出订单支付表"+DateUtils.getDateString(DateUtils.YYYYMMDDHHMMSS)+".xls";
        if(CollectionUtils.isEmpty(tmpList)){
            ExcelExport.exportExcelFile(titleList, dataList, xlsName, 0, request, response);
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        for(OrdInfo tmpOrdInfo : tmpList){
            List<String> data = new ArrayList<String>();
            data.add(tmpOrdInfo.getOrdId()==null?"":String.valueOf(tmpOrdInfo.getOrdId()));
            data.add(tmpOrdInfo.getPayId()==null?"":String.valueOf(tmpOrdInfo.getPayId()));
            data.add(tmpOrdInfo.getTotalMoney()==null?"":String.valueOf((double)(Math.round(tmpOrdInfo.getTotalMoney())/100.0)));
            data.add(tmpOrdInfo.getPayTime()==null?"":sdf.format(tmpOrdInfo.getPayTime()));
            dataList.add(data);
        }
        ExcelExport.exportExcelFile(titleList, dataList, xlsName, 0, request, response);
    }
	
	@RequestMapping(value = { "/pay" }, method = { RequestMethod.POST })
	@ResponseBody
	public JSONObject pay(@RequestParam("idLst") String[] idLst) throws Exception {
		JSONObject ret = new JSONObject();
		try {
			orderInfoSV.pay(Arrays.asList(idLst));
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		}
        ret.put("flag", true);
		return ret;
	}
	
	@RequestMapping(value = { "/detail/{ordId}" }, method = { RequestMethod.GET })
	public String detail(Model model, @PathVariable String ordId) throws Exception {
		try {
			List<OrdInfo> ordLst = orderInfoSV.queryOrdInfoById(ordId);
			if (!CollectionUtils.isEmpty(ordLst)) {
				model.addAttribute("ord", ordLst.get(0));
				model.addAttribute("data", ordLst);
				int totle = 0;
				for (OrdInfo ordInfo : ordLst) {
					totle += ordInfo.getTotalMoney();
					GdsInfoResp gdsInfoResp = gdsInfoSV.queryGdsInfosByGdsId(Long.valueOf(ordInfo.getGdsId()));
					if (!CollectionUtils.isEmpty(gdsInfoResp.getPicLit())) {
						ordInfo.setPicUrl(gdsInfoResp.getPicLit().get(0).getPicUrl());
					}
				}
				model.addAttribute("totle", totle);
			}
		} catch (Exception e) {
			log.error(e);
		}
		return "/busi/order/order-detail";
	}
}
